/**
 * 
 */
package org.ztest.timer;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 抽象的定时单元，一个定时单元由触发时间以及触发行为组成
 * @author lhl
 *
 * 2015年7月23日上午9:01:52
 */
public abstract class DelayItem implements Delayed, Runnable
{
	long nextTriggerTime; // 下一次触发时间
	long uid; // 玩家id
	long delay; // 定时器延时
	
	/**
	 * @param uid 玩家id
	 * @param delay 延时时间
	 * @param unit 时间单位
	 */
	public DelayItem(long uid, long delay, TimeUnit unit)
	{
		this.uid = uid;
		this.delay = unit.toMillis(delay);
		this.nextTriggerTime = nextTriggerTime(this.delay);
	}
	
	/**
	 * 计算定时器触发时间
	 * @param delay
	 * @return 定时器下一次触发时刻
	 */
	private long nextTriggerTime(long delay)
	{
		return delay + System.currentTimeMillis();
	}
	
	/**
	 * 重置定时器触发时间
	 */
	public final void reuse()
	{
		this.nextTriggerTime = nextTriggerTime(this.delay);
	}
	
	@Override
	public final int compareTo(Delayed o)
	{
		if (this == o)
		{
			return 0;
		}
		long diff = this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
		return diff == 0 ? 0 : (diff < 0 ? -1 : 1);
	}

	@Override
	public final long getDelay(TimeUnit unit)
	{
		return unit.convert(nextTriggerTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
	}
}
